package models

import (
	"errors"
	"fmt"
	"time"
)

// FranchiseSettlementEngine 加盟结算引擎
type FranchiseSettlementEngine struct {
	CommissionRules []CommissionRule
	CostRules       []CostRule
	TaxRules        []TaxRule
}

// CommissionRule 佣金规则
type CommissionRule struct {
	RuleID      string  `json:"rule_id"`
	FranchiseID int64   `json:"franchise_id"`
	MinRevenue  float64 `json:"min_revenue"`
	MaxRevenue  float64 `json:"max_revenue"`
	Rate        float64 `json:"rate"`
	Type        string  `json:"type"` // percentage, fixed
	Description string  `json:"description"`
	StartDate   int64   `json:"start_date"`
	EndDate     int64   `json:"end_date"`
	Priority    int     `json:"priority"`
}

// CostRule 成本规则
type CostRule struct {
	RuleID      string  `json:"rule_id"`
	FranchiseID int64   `json:"franchise_id"`
	Type        string  `json:"type"` // platform_fee, service_fee, technology_fee
	Amount      float64 `json:"amount"`
	Rate        float64 `json:"rate"`
	Description string  `json:"description"`
	StartDate   int64   `json:"start_date"`
	EndDate     int64   `json:"end_date"`
}

// TaxRule 税务规则
type TaxRule struct {
	RuleID      string  `json:"rule_id"`
	Type        string  `json:"type"` // vat, income_tax, business_tax
	Rate        float64 `json:"rate"`
	Description string  `json:"description"`
	StartDate   int64   `json:"start_date"`
	EndDate     int64   `json:"end_date"`
}

// SettlementRequest 结算请求
type SettlementRequest struct {
	FranchiseID int64              `json:"franchise_id"`
	StoreID     int64              `json:"store_id"`
	StartDate   int64              `json:"start_date"`
	EndDate     int64              `json:"end_date"`
	Revenue     float64            `json:"revenue"`
	Orders      []*SettlementOrder `json:"orders"`
	Adjustments []Adjustment       `json:"adjustments"`
}

// SettlementOrder 结算订单
type SettlementOrder struct {
	OrderID     int64   `json:"order_id"`
	Amount      float64 `json:"amount"`
	Commission  float64 `json:"commission"`
	PlatformFee float64 `json:"platform_fee"`
	ServiceFee  float64 `json:"service_fee"`
	Tax         float64 `json:"tax"`
	NetAmount   float64 `json:"net_amount"`
}

// Adjustment 调整项
type Adjustment struct {
	Type        string  `json:"type"` // discount, refund, penalty
	Amount      float64 `json:"amount"`
	Description string  `json:"description"`
	Date        int64   `json:"date"`
}

// SettlementResponse 结算响应
type SettlementResponse struct {
	FranchiseID      int64                 `json:"franchise_id"`
	StoreID          int64                 `json:"store_id"`
	SettlementPeriod string                `json:"settlement_period"`
	GrossRevenue     float64               `json:"gross_revenue"`
	NetRevenue       float64               `json:"net_revenue"`
	Commission       float64               `json:"commission"`
	PlatformFee      float64               `json:"platform_fee"`
	ServiceFee       float64               `json:"service_fee"`
	TechnologyFee    float64               `json:"technology_fee"`
	Tax              float64               `json:"tax"`
	Adjustments      float64               `json:"adjustments"`
	FinalAmount      float64               `json:"final_amount"`
	Breakdown        []SettlementBreakdown `json:"breakdown"`
	Orders           []*SettlementOrder    `json:"orders"`
	Status           string                `json:"status"`
	GeneratedAt      int64                 `json:"generated_at"`
}

// SettlementBreakdown 结算明细
type SettlementBreakdown struct {
	Type        string  `json:"type"`
	Description string  `json:"description"`
	Amount      float64 `json:"amount"`
	Rate        float64 `json:"rate"`
	Subtotal    float64 `json:"subtotal"`
}

// PaymentSchedule 付款计划
type PaymentSchedule struct {
	FranchiseID   int64   `json:"franchise_id"`
	SettlementID  string  `json:"settlement_id"`
	TotalAmount   float64 `json:"total_amount"`
	PaymentDate   int64   `json:"payment_date"`
	Status        string  `json:"status"`
	PaymentMethod string  `json:"payment_method"`
	TransactionID string  `json:"transaction_id"`
}

// NewFranchiseSettlementEngine 创建新的加盟结算引擎
func NewFranchiseSettlementEngine() *FranchiseSettlementEngine {
	return &FranchiseSettlementEngine{
		CommissionRules: loadCommissionRules(),
		CostRules:       loadCostRules(),
		TaxRules:        loadTaxRules(),
	}
}

// CalculateSettlement 计算加盟结算
func (fse *FranchiseSettlementEngine) CalculateSettlement(request *SettlementRequest) (*SettlementResponse, error) {
	response := &SettlementResponse{
		FranchiseID:      request.FranchiseID,
		StoreID:          request.StoreID,
		SettlementPeriod: formatSettlementPeriod(request.StartDate, request.EndDate),
		Breakdown:        []SettlementBreakdown{},
		Orders:           request.Orders,
		GeneratedAt:      time.Now().Unix(),
		Status:           "calculated",
	}

	// 验证输入
	if err := fse.validateRequest(request); err != nil {
		return nil, err
	}

	// 计算总收入
	grossRevenue := request.Revenue
	response.GrossRevenue = grossRevenue

	// 计算佣金
	commission := fse.calculateCommission(request.FranchiseID, grossRevenue, request.StartDate, request.EndDate)
	response.Commission = commission
	response.Breakdown = append(response.Breakdown, SettlementBreakdown{
		Type:        "commission",
		Description: "加盟佣金",
		Amount:      grossRevenue,
		Rate:        commission / grossRevenue,
		Subtotal:    commission,
	})

	// 计算平台费用
	platformFee := fse.calculatePlatformFee(request.FranchiseID, grossRevenue, request.StartDate, request.EndDate)
	response.PlatformFee = platformFee
	response.Breakdown = append(response.Breakdown, SettlementBreakdown{
		Type:        "platform_fee",
		Description: "平台服务费",
		Amount:      grossRevenue,
		Rate:        platformFee / grossRevenue,
		Subtotal:    platformFee,
	})

	// 计算服务费用
	serviceFee := fse.calculateServiceFee(request.FranchiseID, grossRevenue, request.StartDate, request.EndDate)
	response.ServiceFee = serviceFee
	response.Breakdown = append(response.Breakdown, SettlementBreakdown{
		Type:        "service_fee",
		Description: "技术服务费",
		Amount:      grossRevenue,
		Rate:        serviceFee / grossRevenue,
		Subtotal:    serviceFee,
	})

	// 计算技术费用
	technologyFee := fse.calculateTechnologyFee(request.FranchiseID, grossRevenue, request.StartDate, request.EndDate)
	response.TechnologyFee = technologyFee
	response.Breakdown = append(response.Breakdown, SettlementBreakdown{
		Type:        "technology_fee",
		Description: "系统使用费",
		Amount:      grossRevenue,
		Rate:        technologyFee / grossRevenue,
		Subtotal:    technologyFee,
	})

	// 计算税费
	tax := fse.calculateTax(grossRevenue, request.StartDate, request.EndDate)
	response.Tax = tax
	response.Breakdown = append(response.Breakdown, SettlementBreakdown{
		Type:        "tax",
		Description: "税费",
		Amount:      grossRevenue,
		Rate:        tax / grossRevenue,
		Subtotal:    tax,
	})

	// 计算调整项
	adjustments := fse.calculateAdjustments(request.Adjustments)
	response.Adjustments = adjustments
	if adjustments != 0 {
		response.Breakdown = append(response.Breakdown, SettlementBreakdown{
			Type:        "adjustments",
			Description: "调整项",
			Amount:      adjustments,
			Rate:        0,
			Subtotal:    adjustments,
		})
	}

	// 计算净收入和最终金额
	netRevenue := grossRevenue - commission - platformFee - serviceFee - technologyFee - tax + adjustments
	response.NetRevenue = netRevenue
	response.FinalAmount = netRevenue

	return response, nil
}

// validateRequest 验证结算请求
func (fse *FranchiseSettlementEngine) validateRequest(request *SettlementRequest) error {
	if request.FranchiseID <= 0 {
		return errors.New("加盟商ID无效")
	}

	if request.StartDate >= request.EndDate {
		return errors.New("开始日期必须早于结束日期")
	}

	if request.Revenue < 0 {
		return errors.New("收入不能为负数")
	}

	return nil
}

// calculateCommission 计算佣金
func (fse *FranchiseSettlementEngine) calculateCommission(franchiseID int64, revenue float64, startDate, endDate int64) float64 {
	var applicableRule *CommissionRule

	// 查找适用的佣金规则
	for _, rule := range fse.CommissionRules {
		if rule.FranchiseID == franchiseID {
			if revenue >= rule.MinRevenue && revenue <= rule.MaxRevenue {
				if startDate >= rule.StartDate && endDate <= rule.EndDate {
					if applicableRule == nil || rule.Priority > applicableRule.Priority {
						applicableRule = &rule
					}
				}
			}
		}
	}

	if applicableRule == nil {
		return revenue * 0.05 // 默认5%佣金
	}

	if applicableRule.Type == "percentage" {
		return revenue * applicableRule.Rate
	} else if applicableRule.Type == "fixed" {
		return applicableRule.Rate
	}

	return 0
}

// calculatePlatformFee 计算平台费用
func (fse *FranchiseSettlementEngine) calculatePlatformFee(franchiseID int64, revenue float64, startDate, endDate int64) float64 {
	fee := 0.0

	for _, rule := range fse.CostRules {
		if rule.FranchiseID == franchiseID && rule.Type == "platform_fee" {
			if startDate >= rule.StartDate && endDate <= rule.EndDate {
				if rule.Amount > 0 {
					fee += rule.Amount
				} else {
					fee += revenue * rule.Rate
				}
			}
		}
	}

	if fee == 0 {
		return revenue * 0.03 // 默认3%平台费
	}

	return fee
}

// calculateServiceFee 计算服务费用
func (fse *FranchiseSettlementEngine) calculateServiceFee(franchiseID int64, revenue float64, startDate, endDate int64) float64 {
	fee := 0.0

	for _, rule := range fse.CostRules {
		if rule.FranchiseID == franchiseID && rule.Type == "service_fee" {
			if startDate >= rule.StartDate && endDate <= rule.EndDate {
				if rule.Amount > 0 {
					fee += rule.Amount
				} else {
					fee += revenue * rule.Rate
				}
			}
		}
	}

	if fee == 0 {
		return revenue * 0.02 // 默认2%服务费
	}

	return fee
}

// calculateTechnologyFee 计算技术费用
func (fse *FranchiseSettlementEngine) calculateTechnologyFee(franchiseID int64, revenue float64, startDate, endDate int64) float64 {
	fee := 0.0

	for _, rule := range fse.CostRules {
		if rule.FranchiseID == franchiseID && rule.Type == "technology_fee" {
			if startDate >= rule.StartDate && endDate <= rule.EndDate {
				if rule.Amount > 0 {
					fee += rule.Amount
				} else {
					fee += revenue * rule.Rate
				}
			}
		}
	}

	if fee == 0 {
		return revenue * 0.01 // 默认1%技术费
	}

	return fee
}

// calculateTax 计算税费
func (fse *FranchiseSettlementEngine) calculateTax(revenue float64, startDate, endDate int64) float64 {
	tax := 0.0

	for _, rule := range fse.TaxRules {
		if startDate >= rule.StartDate && endDate <= rule.EndDate {
			tax += revenue * rule.Rate
		}
	}

	if tax == 0 {
		return revenue * 0.06 // 默认6%税费
	}

	return tax
}

// calculateAdjustments 计算调整项
func (fse *FranchiseSettlementEngine) calculateAdjustments(adjustments []Adjustment) float64 {
	total := 0.0

	for _, adjustment := range adjustments {
		switch adjustment.Type {
		case "discount":
			total -= adjustment.Amount
		case "refund":
			total -= adjustment.Amount
		case "penalty":
			total += adjustment.Amount
		default:
			total += adjustment.Amount
		}
	}

	return total
}

// GeneratePaymentSchedule 生成付款计划
func (fse *FranchiseSettlementEngine) GeneratePaymentSchedule(response *SettlementResponse) *PaymentSchedule {
	return &PaymentSchedule{
		FranchiseID:   response.FranchiseID,
		SettlementID:  fmt.Sprintf("SETTLE_%d_%d", response.FranchiseID, time.Now().Unix()),
		TotalAmount:   response.FinalAmount,
		PaymentDate:   time.Now().AddDate(0, 0, 7).Unix(), // 7天后付款
		Status:        "pending",
		PaymentMethod: "bank_transfer",
	}
}

// GenerateSettlementReport 生成结算报告
func (fse *FranchiseSettlementEngine) GenerateSettlementReport(franchiseID int64, startDate, endDate int64) (*SettlementReport, error) {
	report := &SettlementReport{
		FranchiseID: franchiseID,
		StartDate:   startDate,
		EndDate:     endDate,
		GeneratedAt: time.Now().Unix(),
		Metrics:     make(map[string]float64),
	}

	// 这里应该从数据库查询实际数据
	// 简化处理：返回示例数据
	report.Metrics["total_revenue"] = 100000.0
	report.Metrics["total_commission"] = 5000.0
	report.Metrics["total_platform_fee"] = 3000.0
	report.Metrics["total_service_fee"] = 2000.0
	report.Metrics["total_technology_fee"] = 1000.0
	report.Metrics["total_tax"] = 6000.0
	report.Metrics["net_amount"] = 83000.0

	return report, nil
}

// SettlementReport 结算报告
type SettlementReport struct {
	FranchiseID int64              `json:"franchise_id"`
	StartDate   int64              `json:"start_date"`
	EndDate     int64              `json:"end_date"`
	GeneratedAt int64              `json:"generated_at"`
	Metrics     map[string]float64 `json:"metrics"`
	Details     []SettlementDetail `json:"details"`
}

// SettlementDetail 结算详情
type SettlementDetail struct {
	Date          int64   `json:"date"`
	Revenue       float64 `json:"revenue"`
	Commission    float64 `json:"commission"`
	PlatformFee   float64 `json:"platform_fee"`
	ServiceFee    float64 `json:"service_fee"`
	TechnologyFee float64 `json:"technology_fee"`
	Tax           float64 `json:"tax"`
	NetAmount     float64 `json:"net_amount"`
}

// formatSettlementPeriod 格式化结算周期
func formatSettlementPeriod(startDate, endDate int64) string {
	start := time.Unix(startDate, 0).Format("2006-01-02")
	end := time.Unix(endDate, 0).Format("2006-01-02")
	return fmt.Sprintf("%s 至 %s", start, end)
}

// loadCommissionRules 加载佣金规则
func loadCommissionRules() []CommissionRule {
	return []CommissionRule{
		{
			RuleID:      "COMMISSION_BASIC",
			FranchiseID: 0,
			MinRevenue:  0,
			MaxRevenue:  100000,
			Rate:        0.05,
			Type:        "percentage",
			Description: "基础佣金规则",
			StartDate:   0,
			EndDate:     4102444800,
			Priority:    1,
		},
		{
			RuleID:      "COMMISSION_PREMIUM",
			FranchiseID: 0,
			MinRevenue:  100000,
			MaxRevenue:  500000,
			Rate:        0.04,
			Type:        "percentage",
			Description: "高级佣金规则",
			StartDate:   0,
			EndDate:     4102444800,
			Priority:    2,
		},
		{
			RuleID:      "COMMISSION_VIP",
			FranchiseID: 0,
			MinRevenue:  500000,
			MaxRevenue:  999999999,
			Rate:        0.03,
			Type:        "percentage",
			Description: "VIP佣金规则",
			StartDate:   0,
			EndDate:     4102444800,
			Priority:    3,
		},
	}
}

// loadCostRules 加载成本规则
func loadCostRules() []CostRule {
	return []CostRule{
		{
			RuleID:      "PLATFORM_FEE",
			FranchiseID: 0,
			Type:        "platform_fee",
			Rate:        0.03,
			Description: "平台服务费",
			StartDate:   0,
			EndDate:     4102444800,
		},
		{
			RuleID:      "SERVICE_FEE",
			FranchiseID: 0,
			Type:        "service_fee",
			Rate:        0.02,
			Description: "技术服务费",
			StartDate:   0,
			EndDate:     4102444800,
		},
		{
			RuleID:      "TECHNOLOGY_FEE",
			FranchiseID: 0,
			Type:        "technology_fee",
			Rate:        0.01,
			Description: "系统使用费",
			StartDate:   0,
			EndDate:     4102444800,
		},
	}
}

// loadTaxRules 加载税务规则
func loadTaxRules() []TaxRule {
	return []TaxRule{
		{
			RuleID:      "VAT",
			Type:        "vat",
			Rate:        0.06,
			Description: "增值税",
			StartDate:   0,
			EndDate:     4102444800,
		},
		{
			RuleID:      "BUSINESS_TAX",
			Type:        "business_tax",
			Rate:        0.05,
			Description: "营业税",
			StartDate:   0,
			EndDate:     4102444800,
		},
	}
}
